package cn.sciento.starter.social.wechat.enterprise.api;

import com.google.common.base.Charsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.starter.social.core.common.api.AbstractSocialApi;
import cn.sciento.starter.social.core.exception.CommonSocialException;
import cn.sciento.starter.social.core.exception.ProviderUserNotFoundException;
import cn.sciento.starter.social.core.provider.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;

public class DefaultWechatEnterpriseApi extends AbstractSocialApi implements WechatEnterpriseApi {
  private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWechatEnterpriseApi.class);
  
  private String userInfoUrl;
  
  private String openIdUrl;
  
  private String code;
  
  public DefaultWechatEnterpriseApi(String accessToken, Provider provider) {
    super(accessToken.split("#")[0]);
    if (accessToken.contains("#")) {
      String[] arr = accessToken.split("#");
      this.code = arr[1];
    } 
    this.openIdUrl = provider.getOpenIdUrl() + "?code={code}";
    this.userInfoUrl = provider.getUserInfoUrl() + "?userid={userId}";
  }
  
  public WechatEnterpriseUser getUser(String providerUserId) {
    String userId;
    if (!isAuthorized())
      throw new CommonSocialException("hoth.social.userNotAuthorized"); 
    if (StringUtils.isBlank(providerUserId)) {
      userId = getUserId();
    } else {
      userId = providerUserId;
    } 
    HashMap<String, String> userInfo = (HashMap<String, String>)getRestTemplate().getForObject(this.userInfoUrl, HashMap.class, new Object[] { userId });
    if (userInfo == null || StringUtils.isBlank(userInfo.get("name"))) {
      LOGGER.info("not found provider user, result user={}", userInfo);
      throw new ProviderUserNotFoundException("hoth.social.providerUserNotFound");
    } 
    WechatEnterpriseUser user = new WechatEnterpriseUser();
    user.setName(userInfo.get("name"));
    user.setAvatar(userInfo.get("avatar"));
    user.setMobile(userInfo.get("mobile"));
    user.setUserid(userId);
    return user;
  }
  
  private String getUserId() {
    Map<String, String> openIdResult = (Map<String, String>)getRestTemplate().getForObject(this.openIdUrl, Map.class, new Object[] { this.code });
    if (openIdResult == null || openIdResult.isEmpty()) {
      LOGGER.warn("request social user's openId return error, result={}", openIdResult);
      throw new CommonSocialException("hoth.social.openIdNotFound");
    } 
    return openIdResult.get("UserId");
  }
  
  protected List<HttpMessageConverter<?>> getMessageConverters() {
    List<HttpMessageConverter<?>> converters = super.getMessageConverters();
    converters.remove(0);
    converters.add(new StringHttpMessageConverter(Charsets.UTF_8));
    return converters;
  }
}
